import Flv from 'flv.js'
import Hls from 'hls.js'
import dashjs from 'dashjs'
import {MuiPlayerResult} from "./MuiPlayerUtils";

export interface Decoder {
  type: string,

  func(): void
}

export interface ParseConfigParams {
  muiPlayer?: MuiPlayerResult;
  otherDecoders?: Decoder[];

  notFindCall?(): void
}

export function decoderConfig(params: ParseConfigParams) {
  return function (video: HTMLVideoElement, src: string) {
    let _destroy = (kernel:{destroy:Function}) => {
      setTimeout(() => {
        if(params.muiPlayer) {
          params.muiPlayer.on('error', function () {
            kernel.destroy();
          })
        }
      }, 500);
    }
    const decodes: Decoder[] = [
      {
        type: '.mp4',
        func: () => {
          video.src = src;
        }
      },
      {
        type: '.m3u8',
        func: () => {
          let hlsConfig = {
            autoStartLoad: true,
            debug: false,
          }
          let hls = new Hls(hlsConfig);
          hls.attachMedia(video);
          hls.on(Hls.Events.MEDIA_ATTACHED, function () {
            hls.loadSource(src);
          })

          hls.on(Hls.Events.ERROR, function (errMes) {
            console.error(errMes);
            // 发送错误报告
            params.muiPlayer?.sendError(errMes);
          });
          _destroy(hls)
        }
      },
      {
        type: '.flv',
        func: () => {
          let flvConfig = {
            type: 'flv',
            url: src,
          }
          let flv = Flv.createPlayer(flvConfig);
          flv.attachMediaElement(video);
          flv.load();

          flv.on(Flv.Events.ERROR, function (errMes) {
            console.error(errMes);
            // 发送错误报告
            params.muiPlayer?.sendError(errMes);
          });
          _destroy(flv)
        }
      },
      {
        type: '.mpd',
        func: () => {
          let dashMedia = dashjs.MediaPlayer().create();
          dashMedia.initialize(video, src, false);
          dashMedia.on(dashjs.MediaPlayer.events.ERROR, function (errMes) {
            console.error(errMes);
            // 发送错误报告
            if ("event" in errMes) {
              params.muiPlayer?.sendError(<string>errMes.event);
            } else {
              params.muiPlayer?.sendError(errMes.error.message);
            }
            dashMedia.reset();
          })
          _destroy(dashMedia)
        }
      },
      ...(params.otherDecoders || [])
    ]
    let find: Decoder
    setTimeout(() => {
      if (params.muiPlayer?.nowDecoder === 'auto') {
        find = decodes.find(i => src.indexOf(i.type) !== -1) || {} as Decoder;
      } else {
        find = decodes.find(i => i.type === params.muiPlayer?.nowDecoder) || {} as Decoder;
      }
      if (find) {
        find.func()
      } else {
        if (params.notFindCall) {
          params.notFindCall()
        } else {
          alert('没找到解码器')
        }
      }
    })
  };
}
